package com.example.template.common.storage.impl;

import com.aliyun.oss.OSSClient;
import com.example.template.common.api.ApiCodeConstant;
import com.example.template.common.exception.GlobalException;
import com.example.template.common.storage.FileOperation;
import com.example.template.common.storage.minio.MinioUtil;
import com.example.template.common.storage.minio.config.MinioConfig;
import com.example.template.utils.FileKit;
import com.upyun.UpYunUtils;
import io.minio.MinioClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;

/**
 * @className: MinioStorageImpl
 * @description: TODO 类描述
 * @author: Kuangkeli
 * @date: 2024/01/22 20:28
 **/
@Component
public class MinioStorageImpl extends AbstractStorage implements FileOperation {
    private static Logger logger = LoggerFactory.getLogger(MinioStorageImpl.class);

    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioUtil minioUtil;

    //重写文件操作
    @Override
    public String writeToStore(byte[] bytes, String pathAndFileName) throws Exception {
        if (StringUtils.isAnyBlank(minioConfig.getUrl(), minioConfig.getBucketName())) {
            throw new GlobalException(ApiCodeConstant.RESULT_OTHER_EXCEPTION,"请先在后台设置Minio配置信息");
        }
        return minioUtil.putObject(new ByteArrayInputStream(bytes),pathAndFileName);
    }

    @Override
    public void deleteFile(String storePath) {
        String bucket = minioConfig.getBucketName();
        String endpoint = minioConfig.getUrl();
        String path = StringUtils.remove(storePath, "//" + bucket.trim() + "." + endpoint.trim() + "/");
        try {
          minioUtil.delete(bucket,path);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    private MinioClient builder() {
        if (StringUtils.isAnyBlank(minioConfig.toString())) {
            throw new GlobalException(ApiCodeConstant.RESULT_OTHER_EXCEPTION,"请先在后台设置Minio配置信息");
        }
        return minioConfig.getMinioClient();
    }
}
